#include "temp_functions.h"



int ReadFile(struct sensor *info, const char filename[]) 
{
    FILE *in;
    if((in=fopen(filename, "r"))==NULL) {
    printf ("Cannot open file.\n");
    printf("'-h' for help\n");
    return -1;
    }
    int i = 0;
    int n=0;
    while((n=fscanf(in,"%d ; %d ; %d ; %d ; %d ; %d",&info[i].year,&info[i].month,&info[i].day,&info[i].hour,&info[i].minute,&info[i].t))>0)
    {
        if(n<6)
        {
            char s[100];
            n = fscanf(in,"%[^\n]",s);
            printf("ERROR in line %d, file: <%s> data: <%s> line skiped\n",i+1,filename,s);
            i--;
        }
        i++;
    }    

    fclose(in);
    return i;
}

void print(struct sensor *info, int number)
{
    printf("====================================\n");
    for (int i = 0; i < number; i++)
    {
        printf("%6d %8d-%02d-%02d %02d:%02d t=%3d\n",
               i,
               info[i].year,
               info[i].month,
               info[i].day,
               info[i].hour,
               info[i].minute,
               info[i].t);
    }
}


int MaxYear(struct sensor *info, int n)
{
    int max=info[0].t;
    for (int i=1; i<n; i++)
    {
        if(info[i].t>max)
        {
            max=info[i].t;
        }
    }
    return max;
}

int MinYear(struct sensor *info, int n)
{
    int min=info[0].t;
    for (int i=1; i<n; i++)
    {
        if(info[i].t<min)
        {
            min=info[i].t;
        }
    }
    return min;
}

float MeanYear(struct sensor *info, int n)
{
    int sum=0;
    for (int i=0; i<n; i++)
    {
        sum+=info[i].t;
    }
    return (float)sum/n;
}

int MaxMonth(struct sensor *info, int n,int month)
{
    int max=-99;
    for (int i=1; i<n; i++)
    {
        if((info[i].month==month)&(info[i].t>max))
        {
            max=info[i].t;
        }
    }
    return max;
}

int MinMonth(struct sensor *info, int n,int month)
{
    int min=99;
    for (int i=1; i<n; i++)
    {
        if((info[i].month==month)&(info[i].t<min))
        {
            min=info[i].t;
        }
    }
    return min;
}

float MeanMonth(struct sensor *info, int n,int month)
{
    int sum=0;
    int counter=0;
    for (int i=0; i<n; i++)
    {
        if(info[i].month==month)
        {
            sum+=info[i].t;
            counter++;
        }
        
    }
    return (float)sum/counter;
}